<template>
    <div>
        <div class="btn-block">
            <el-button type="primary" size="small" plain :loading="exportOrderLoading" @click="exportOrder">订单导出</el-button>
            <el-upload
                    style="display: inline-block; margin: 0 12px;"
                    :action="upladUrl"
                    accept=".xls,.xlsx"
                    :show-file-list="false"
                    name="file"
                    :on-success="(res)=>{ handleFileSuccess(res, 'Order') }"
                    :on-error="(res)=>{ handleFileError(res, 'Order') }"
                    :before-upload="(file)=>{ beforeFileUpload(file, 'Order') }"
                    :disabled="!isRemit || importOrderLoading">
                <el-button type="warning" size="small" :loading="importOrderLoading" :disabled="!isRemit || importOrderLoading" plain>订单导入
                </el-button>
            </el-upload>

            <el-button type="primary" size="small" plain :loading="exportBalanceLoading" @click="exportBalanceList">对账单导出</el-button>
            <el-upload
                    style="display: inline-block; margin: 0 12px;"
                    :action="upladUrl"
                    accept=".xls,.xlsx"
                    :show-file-list="false"
                    name="file"
                    :on-success="(res)=>{ handleFileSuccess(res, 'Balance') }"
                    :on-error="(res)=>{ handleFileError(res, 'Balance') }"
                    :before-upload="(file)=>{ beforeFileUpload(file, 'Balance') }"
                    :disabled="!isRemit || importBalanceLoading">
                <el-button type="warning" size="small" :loading="importBalanceLoading" :disabled="!isRemit || importBalanceLoading" plain>对账单导入
                </el-button>
            </el-upload>
            <el-button type="success" size="small" plain :loading="generateBillLoading" @click="generateBill">生成报表</el-button>
        </div>
        <el-form ref="searchForm" class="search-block" :model="listQuery" label-position="left" label-width="110px">
            <el-row :gutter="50">
                <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="商品款号：" prop="goodsSn">
                        <el-input @keyup.enter.native="search" v-model="listQuery.goodsSn" placeholder="商品款号"
                                  maxlength="50" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="商品名称：" prop="goodsName">
                        <el-input @keyup.enter.native="search" v-model="listQuery.goodsName" placeholder="商品名称" maxlength="60" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="SKU：" prop="skuCode">
                        <el-input @keyup.enter.native="search" v-model="listQuery.skuCode" placeholder="SKU" maxlength="50" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="状态：" prop="status">
                        <el-select v-model="listQuery.status" placeholder="请选择" clearable>
                            <el-option v-for="(item, index) in statusType" :label="item" :value="index" :key="index"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="" class="btn-item">
                <el-button type="primary" size="mini" icon="el-icon-search" plain @click="search">搜索</el-button>
                <span class="btn-reset" @click="resetForm('searchForm')">清空搜索条件</span>
            </el-form-item>
        </el-form>
        <el-table :data="list" v-loading="listLoading" header-row-class-name="table-header" element-loading-text="给我一点时间" border highlight-current-row>
            <el-table-column align="center" label="商品名称" prop="goodsName" min-width="100"></el-table-column>
            <el-table-column align="center" label="商品款号" prop="goodsSn" min-width="100"></el-table-column>
            <el-table-column align="center" label="SKU" prop="skuCode" min-width="100"></el-table-column>
            <el-table-column align="center" label="结算单价" prop="price" min-width="100"></el-table-column>
            <el-table-column align="center" label="数量" prop="number" min-width="100">
                <template slot-scope="scope">
                    <span v-text="scope.row.checkNumber || 0"></span> /
                    <span v-text="scope.row.number"></span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="总金额" prop="totalAmount" min-width="100"></el-table-column>
            <el-table-column align="center" label="状态" prop="status" width="100">
                <template slot-scope="scope">
                    <span v-text="statusType[scope.row.status]"></span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="实际出账时间" width="160">
                <template slot-scope="scope">
                    <span v-text="formatDate(scope.row.actualBillingTime, 'yyyy-MM-dd hh:mm:ss')"></span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="190">
                <template slot-scope="scope">
                    <el-button type="text" size="mini" @click="$router.push({ name: 'balanceOrderList', params: {id: scope.row.id}})">查看订单</el-button>
                    <el-button v-if="scope.row.status && scope.row.status!==5" type="text" size="mini" @click="reset(scope.row.id)">重置
                    </el-button>
                    <el-button v-if="scope.row.status===1 || scope.row.status===3" type="text" size="mini" @click="operate(scope.row.id, 1)">审核通过
                    </el-button>
                    <el-button v-if="scope.row.status===2" type="text" size="mini" @click="operate(scope.row.id, 2)">出账
                    </el-button>
                    <span v-if="scope.row.status===5"> - </span>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page.sync="listQuery.pageNum"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="listQuery.pageSize"
                background
                layout="total, sizes, prev, pager, next, jumper"
                :total="listTotal">
        </el-pagination>
    </div>
</template>
<script>
  import moment from 'moment'
  export default {
    name: 'balanceDetailList',
    props: {
      id: {
        default: ''
      }
    },
    data() {
      return {
        listLoading: false,
        listQuery: {
          id: this.id,
          goodsSn: '',
          goodsName: '',
          skuCode: '',
          status: '',
          pageNum: 1,
          pageSize: 10
        },
        list: [],
        listTotal: 0,
        isRemit: 0,

        operateType: ['', '审核', '出账', '打款'],
        statusType: ['未验证', '未审核', '审核通过', '已重置', '已出对账单', '已打款'],

        exportOrderLoading: false,
        importOrderLoading: false,
        exportBalanceLoading: false,
        importBalanceLoading: false,
        generateBillLoading: false
      }
    },
    created() {
      this.getList();
    },
    methods: {
      getList() {
        this.listLoading = true;
        this.request({
          url: '/bsnl-merchant-bill/bill/details',
          method: 'post',
          data: this.listQuery
        }).then(({data}) => {
          this.isRemit = data.isRemit;
          this.list = data.rows;
          this.listTotal = data.total;
          this.listLoading = false;
        }).catch(err => {
          console.log(err);
          this.list = [];
          this.listTotal = 0;
          this.listLoading = false;
        });
      },
      search() {
        this.listQuery.pageNum = 1;
        this.getList();
      },
      // 清空搜索条件
      resetForm(formName) {
        this.$nextTick(() => {
          this.$refs[formName].resetFields()
        })
      },
      handleSizeChange(value) {
        this.listQuery.pageSize = value;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val;
        this.getList();
      },
      operate(id, type) {
        if (id) {
          this.$confirm(`确定进行【${this.operateType[type]}】操作?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.request({
              url: '/bsnl-merchant-bill/bill/operate',
              method: 'post',
              data: {
                type,
                ids: [id]
              }
            }).then(() => {
              this.$message.success('操作成功');
              this.getList();
            }).catch(err => {
              console.log(err);
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            });
          });
        }
      },
      reset(id) {
        if (id) {
          this.$confirm(`确定进行【重置】操作?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.request({
              url: `/bsnl-merchant-bill/bill/reset?id=${id}`,
              method: 'get'
            }).then(() => {
              this.$message.success('重置成功');
              this.getList();
            }).catch(err => {
              console.log(err);
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            });
          });
        }
      },
      // 订单导出
      exportOrder(){
        this.exportOrderLoading = true;
        this.request({
          url: '/bsnl-merchant-order/billInfo/exportBillInfo',
          method: 'post',
          data: {
            id: this.id
          },
          responseType: 'arraybuffer'
        }).then((data) => {
          let date = moment().format('YYYYMMDD/HHmmss').replace(/\//g, '_');
          let filename = `订单${date}.xls`;
          this.downloadFile(data, filename);
          this.exportOrderLoading = false;
        }).catch(err => {
          console.log(err);
          this.exportOrderLoading = false;
        });
      },
      // 对账单导出
      exportBalanceList(){
        this.exportBalanceLoading = true;
        this.request({
          url: '/bsnl-merchant-order/bill/exportBill',
          method: 'get',
          params: {
            id: this.id
          },
          responseType: 'arraybuffer'
        }).then((data) => {
          let date = moment().format('YYYYMMDD/HHmmss').replace(/\//g, '_');
          let filename = `对账单${date}.xls`;
          this.downloadFile(data, filename);
          this.exportBalanceLoading = false;
        }).catch(err => {
          console.log(err);
          this.exportBalanceLoading = false;
        });
      },
      beforeFileUpload(file, type) {
        if (file.size > 50 * 1024 * 1024) {
          this.$message.error('文件不能大于50M');
          return false
        } else {
          this[`import${type}Loading`] = true;
        }
      },
      handleFileError(res, type) {
        this.$message({
          message: res && res.message? JSON.parse(res.message).message : '服务器异常',
          type: 'error',
          duration: 5 * 1000
        });
        this[`import${type}Loading`] = false;
      },
      // 导入订单/对账单
      handleFileSuccess(res, type) {
        if(res.status===200 && res.filePath){
          this.request({
            url: type==='Order'?'/bsnl-merchant-order/billInfo/importBillInfo':'/bsnl-merchant-order/bill/importBill',
            method: 'get',
            params: {
              id: this.id,
              fileUrl: res.filePath
            }
          }).then(({data}) => {
            if (data && data.failureList && data.failureList.length) {
              let result = '';
              data.failureList.map(item => {
                result += (item + '<br/>')
              });
              this.$alert(result, '导入结果', {
                confirmButtonText: '确定',
                dangerouslyUseHTMLString: true
              });
            } else if(data && data.successList && data.successList.length){
              this.getImportResult({
                type,
                code: data.successList[0]
              })
            }
          }).catch(err => {
            console.log(err);
          });
        } else {
          this.$message({
            message: res && res.message? res.message : '服务器异常',
            type: 'error',
            duration: 5 * 1000
          });
          this[`import${type}Loading`] = false;
        }
      },
      generateBill(){
        this.generateBillLoading = true;
        this.request({
          url: '/bsnl-merchant-order/billInfo/generateBill',
          method: 'get',
          params: {
            id: this.id
          },
          responseType: 'arraybuffer'
        }).then((data) => {
          let date = moment().format('YYYYMMDD/HHmmss').replace(/\//g, '_');
          let filename = `报表${date}.xls`;
          this.downloadFile(data, filename);
          this.generateBillLoading = false;
        }).catch(err => {
          console.log(err);
          this.generateBillLoading = false;
        });
      },

      getImportResult(item){
        let timer = setInterval(()=>{
          this.request({
            url: '/bsnl-merchant-order/importLog/getLastOne',
            method: 'get',
            params: {
              codes: item.code
            }
          }).then(({data}) => {
            if(data && data.status){
              clearInterval(timer);
              if(data.type){
                this.$message.success(data.description||'导入成功')
              } else {
                this.$alert(data.description, '导入结果', {
                  confirmButtonText: '确定',
                  dangerouslyUseHTMLString: true
                })
              }
              this[`import${item.type}Loading`] = false;
              this.getList()
            }
          }).catch(err => {
            console.log(err);
          });
        }, 1500);
      }
    }
  }
</script>
